package cn.jiyun.consumer.controller;

import cn.jiyun.consumer.client.UserClient;
import cn.jiyun.consumer.pojo.User;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@RequestMapping("/consumer")
@DefaultProperties(defaultFallback = "defaultFallback")
public class ConsumerController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private UserClient userClient;

    @GetMapping("/findById/{id}")
    //@HystrixCommand
    //@HystrixCommand(fallbackMethod = "fidnByIdFallBack")
    public User findById(@PathVariable("id") Long id) {
        //获取服务列表的信息
        /*List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
        ServiceInstance serviceInstance = instances.get(0);
        String url = "http://"+serviceInstance.getHost()+":"+serviceInstance.getPort()+"/user/findById/" + id;*/
        /*if (id==1){
            throw new RuntimeException("服务端异常");
        }
        String url = "http://user-service/user/findById/" + id;
        String user = restTemplate.getForObject(url, String.class);*/
        User user = userClient.queryById(id);
        return user;
    }
    public String fidnByIdFallBack(Long id){
        return "网络问题，请稍后重试";
    }
    public String defaultFallback(){
        return "默认服务降级逻辑执行了";
    }
}
